package von.seiji.cn;

import von.seiji.cn.asset.Algorithm;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public abstract class RSAUtil {

    public static KeyPair getKeyPair() {
        KeyPairGenerator keyPairGenerator = null;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance(Algorithm.rsa.value());
            SecureRandom secureRandom = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes("utf-8"));
            keyPairGenerator.initialize(2048, secureRandom);    // 这里可以是512,1024、2048 初始化一个密钥对(8,9,10..)<<6
            return keyPairGenerator.generateKeyPair();
        } catch (Exception e) {
        }
        return null;
    }

    public static String pickPublicKey(KeyPair keyPair) {
        PublicKey publicKey = keyPair.getPublic();
        byte[] bytes = publicKey.getEncoded();
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static String picPrivateKey(KeyPair keyPair) {
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] bytes = privateKey.getEncoded();
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static PublicKey str2PublicKey(String pubStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] bytes = Base64.getDecoder().decode(pubStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.rsa.value());
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    public static PrivateKey str2PrivateKey(String priStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] bytes = Base64.getDecoder().decode(priStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.rsa.value());
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    public static byte[] encrypt(String content, PublicKey publicKey) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(Algorithm.rsa.value());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(content.getBytes());
        } catch (Exception e) {
        }
        return null;
    }

    public static String decrypt(byte[] content, PrivateKey privateKey) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(Algorithm.rsa.value());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] bytes = cipher.doFinal(content);
            return new String(bytes);
        } catch (Exception e) {
        }
        return null;
    }
}